<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> svg ViewBox 使用演示 </title>
</head>
<style>
svg {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 300px;
    height: 200px;
    margin-top: -100px;
    margin-left: -150px;
    background: white;
    border: 1px solid green;
}
input[type=number] {
    width: 50px;
}
</style>
<body>
<h1>ViewBox 演示</h1>

<form id="form">
    <p>viewBox</p>

    <label>x: <input id="vx" type="number" value="0"></label>
    <label>y: <input id="vy" type="number" value="0"></label>
    <label>width: <input id="vw" type="number" value="300"></label>
    <label>height: <input id="vh" type="number" value="200"></label>

    <p>preserveAspectRatio</p>
    <label>align: 
        <select id="align">
            <option value="none">none</option>
            <option value="xMinYMin">xMinYMin</option>
            <option value="xMidYMin">xMidYMin</option>
            <option value="xMaxYMin">xMaxYMin</option>
            <option value="xMinYMid">xMinYMid</option>
            <option value="xMidYMid" selected>xMidYMid</option>
            <option value="xMaxYMid">xMaxYMid</option>
            <option value="xMinYMax">xMinYMax</option>
            <option value="xMidYMax">xMidYMax</option>
            <option value="xMaxYMax">xMaxYMax</option>
        </select>
    </label>

    <label>meetOrSlice: 
        <select id="meetOrSlice">
            <option value="meet">meet</option>
            <option value="slice">slice</option>
        </select>
    </label>
</form>

<p>
    <svg id="svg" xmlns="http://www.w3.org/2000/svg">
        <!--Face-->
        <circle cx="100" cy="100" r="90" fill="#39F" />
        <!--Eyes-->
        <circle cx="70" cy="80" r="20" fill="white" />
        <circle cx="130" cy="80" r="20" fill="white" />
        <circle cx="65" cy="75" r="10" fill="black" />
        <circle cx="125" cy="75" r="10" fill="black"/>
        <!--Smile-->
        <path d="M 50 140 A 60 60 0 0 0 150 140" stroke="white" stroke-width="3" fill="none" />
        <rect id="viewBoxIndicator" stroke="red" stroke-width="3.5" fill="none" />
    </svg>
</p>

<script>
const update = () => {
    const viewBox =  [vx.value, vy.value, vw.value, vh.value].join(' ');
    const preserveAspectRatio = [align.value, meetOrSlice.value].join(' ');

    // const svg = document.createElementNS("http://www.w3.org/2000/svg", 'svg'); // 可以省略

    svg.setAttribute('viewBox', viewBox);
    svg.setAttribute('preserveAspectRatio', preserveAspectRatio);

    const rect = viewBoxIndicator;
    rect.setAttribute('x', vx.value);
    rect.setAttribute('y', vy.value);
    rect.setAttribute('width', vw.value);
    rect.setAttribute('height', vh.value);
}

form.addEventListener('input', update);

update();
</script>
</body>
</html>
